#include "avformat.h"
#include "rawdec.h"

static int h265_probe(AVProbeData *p)
{
    uint32_t code= -1;
    int sps=0, pps=0, idr=0, res=0, sli=0;
    int i;
    for(i=0; i<p->buf_size; i++){
        code = (code<<8) + p->buf[i];
        if ((code & 0xffffff00) == 0x100) {
            int ref_flg= (code>>6)&1;
            int type   = (code>>1) & 0x3F;
            static const int8_t ref_zero[64]={
               -1, 0, 0, 0, 0, 0, 0, 0,
                2,-1,-1,-1,-1,-1,-1,-1,
               -1,-1,-1,-1,-1,-1,-1,-1,
               -1, 2, 2, 2, 2, 0, 0, 1,
               -1,-1,-1,-1,-1,-1,-1,-1,
               -1,-1,-1,-1,-1,-1,-1,-1,
               -1,-1,-1,-1,-1,-1,-1,-1,
               -1,-1,-1,-1,-1,-1,-1,-1,
            };

            if(code & 0x80) //forbidden bit
                return 0;

            if(ref_zero[type] == 1 && ref_flg)
                return 0;
            if(ref_zero[type] == 2 && !ref_flg)
                return 0;
            if(ref_zero[type] == -1)
                res++;
#if 0			
{
static int frame = 0;
if( frame++ < 10 )
{
av_log(NULL, AV_LOG_DEBUG,"type=%d,code=%x\r\n",type,code);
}
}
#endif
            switch(type){
            case     1:
            case     2:
            case     3:
            case     4:
            case     5:
            case     6:
            case     7:   sli++; break;
            case     19:   idr++; break;
            case    33:   sps++; break;
            case    34:   pps++; break;
            }
        }
    }
//av_log(NULL, AV_LOG_DEBUG,"h265_probe (%d %d %d %d) %d %d\r\n",sps,pps,idr,sli,res,p->buf_size);
    if(sps && pps && (idr||sli>3) /*&& res<(sps+pps+idr)*/)
        return AVPROBE_SCORE_MAX/2+1; // +1 for .mpg
    return 0;
}

FF_DEF_RAWVIDEO_DEMUXER(h265 , "raw H.265 video format", h265_probe, "h265,hevc,x265,265", AV_CODEC_ID_H265)
